package com.inspectortime.calendar;

import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.inspectortime.domain.Inspector;
import com.inspectortime.service.ZipCodeSearchService;

/**
 * An in-memory representation of one or more inspector calendars with
 * convenience methods that are useful for rendering/traversing
 * 
 * @author mKvalsvik
 * 
 */
public class MultiInspectorCalendar {

	private Date from;
	private Date to;
	Map<Inspector, InspectorCalendar> inspectorCalendarsByInspector = new LinkedHashMap<Inspector, InspectorCalendar>();

	public MultiInspectorCalendar(Date fromDate, Date toDate,
			Collection<Inspector> inspectors) {
		this.from = fromDate;
		this.to = toDate;
		initializeInspectorCalendars(inspectors);
	}
	
	public MultiInspectorCalendar(Date fromDate, int noOfDaysForward,
			Collection<Inspector> inspectors) {
		if (from != null) {
			this.from = fromDate;
		} else {
			// Default to now
			this.from = new Date();
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(this.from);
		cal.add(Calendar.DATE, noOfDaysForward);
		this.to = cal.getTime();		
		initializeInspectorCalendars(inspectors);
	}
	
	public MultiInspectorCalendar(int noOfDaysForward,
			Collection<Inspector> inspectors) {
		this(null, noOfDaysForward, inspectors);
	}

	 private void initializeInspectorCalendars(Collection<Inspector> inspectors) {
		 for (Inspector inspector : inspectors) {	 
			InspectorCalendar days = new InspectorCalendar(from, to, inspector);
			this.inspectorCalendarsByInspector.put(inspector, days);
		}
	 }
	 
	/**
	 * Prepare a map consisting of an inspector and his associated schedule
	 * days. Due to limitations of the view, we'll need to use inspector id as
	 * keys, rather than the actual inspector object
	 */
	public Map<String, List<Day>> dayListByInspectorId() {
		Map<String, List<Day>> daysById = new LinkedHashMap<String, List<Day>>();

		for (Inspector inspector : inspectorCalendarsByInspector.keySet()) {
			InspectorCalendar inspectorCalendar = inspectorCalendarsByInspector
					.get(inspector);
			daysById.put(inspector.getId().toString(), inspectorCalendar
					.getDayList());
		}

		return daysById;
	}
	
	public void disableFarAwayTimeslots(ZipCodeSearchService zipCodeSearchService, String newInspectionZip) {
		for (InspectorCalendar inspectorCalendar : inspectorCalendarsByInspector.values()) {
			inspectorCalendar.disableFarAwayTimeslots(zipCodeSearchService, newInspectionZip);
		}
	}
	
	public void markScheduledAsUnavailable() {
		for (InspectorCalendar inspectorCalendar : inspectorCalendarsByInspector.values()) {
			inspectorCalendar.markScheduledAsUnavailable();
		}
	}
}
